mui.init({});
var userinfo = app.getState() || {};
var uid = userinfo.user_id;

mui.plusReady(function() {
	document.getElementById('do_add').addEventListener('tap', function() {
		var recommend_type = $('input:radio[name="recommend_type"]:checked').val();

		var Info = {
			user_id: uid,
			goods_name: document.getElementById('textarea').value.trim(),
			shop_price: document.getElementById('shop_price').value.trim(),
			store_count: document.getElementById('store_count').value.trim(),
			shipping_price: document.getElementById('shipping_price').value.trim(),
			goods_remark: document.getElementById('goods_remark').value.trim(),
			service_tel: document.getElementById('service_tel').value.trim(),
			recommend_type:recommend_type,
			_token: userinfo.token
		};
		document.getElementById('do_add').disabled = "disabled";
		plus.nativeUI.showWaiting();

		if(recommend_type > 1){
			if(!confirm("您正在选择付费推广商品，具体费用以公告信息为准")){
				plus.nativeUI.closeWaiting();
				document.getElementById('do_add').disabled = "";
				return false;
			}
		}

		if(Info.goods_name == '') {
			mui.alert('商品名称不能为空');
			plus.nativeUI.closeWaiting();
			document.getElementById('do_add').disabled = "";
			return false;
		}
		if(Info.goods_name.length > 30) {
			mui.alert('商品名称不能大于30个字');
			plus.nativeUI.closeWaiting();
			document.getElementById('do_add').disabled = "";
			return false;
		}
		if(Info.shop_price == '' || Info.shop_price <= 0) {
			mui.alert('商品价格要大于0');
			plus.nativeUI.closeWaiting();
			document.getElementById('do_add').disabled = "";
			return false;
		}
		if(Info.store_count == '' || Info.store_count <= 0) {
			mui.alert('商品库存要大于0');
			plus.nativeUI.closeWaiting();
			document.getElementById('do_add').disabled = "";
			return false;
		}
		if(Info.goods_remark == '') {
			mui.alert('商品描述不能为空');
			plus.nativeUI.closeWaiting();
			document.getElementById('do_add').disabled = "";
			return false;
		}
		if(Info.service_tel == '') {
			mui.alert('客服电话不能为空');
			plus.nativeUI.closeWaiting();
			document.getElementById('do_add').disabled = "";
			return false;
		}
		if(document.getElementById('upload_original_img').innerHTML != '已选择图片') {
			mui.alert('商品图片不能为空');
			plus.nativeUI.closeWaiting();
			document.getElementById('do_add').disabled = "";
			return false;
		}

		if(document.getElementById('original_img').src != '') {
			//var base_img=uploadImg(document.getElementById('original_img').src);
			Info.original_img = document.getElementById('original_img').src;
		}

		if($('.add-img .des-img #goods_images li').length > 0) {
			var img_arr = new Array();
			$('.add-img .des-img #goods_images li').each(function(index) {
				//var base_img=uploadImg($(this).find('img').attr('src'));
				img_arr.push($(this).find('img').attr('src'));
			});
			/*var base_img2=uploadImg(document.getElementById('original_img').src);
			img_arr.push(base_img2);*/

			Info.goods_images = img_arr;
		}

		if($('.goods-des .des-img #goods_detail_img li').length > 0) {
			var img_arr2 = new Array();
			$('.goods-des .des-img #goods_detail_img li').each(function(index) {
				//var base_img=uploadImg($(this).find('img').attr('src'));
				img_arr2.push($(this).find('img').attr('src'));
			});
			Info.goods_detail_images = img_arr2;
		}
		//console.log(JSON.stringify(Info.original_img));

		mui.ajax({
			url: apiurl + "Store/add_shop/",
			data: Info,
			async: true,
			dataType: 'json',
			crossDomain: true, //强制使用5+跨域
			type: 'post',
			timeout: 10000,
			success: function(res) {
				plus.nativeUI.closeWaiting();
				console.log(JSON.stringify(res));
				if(res.status == -3) {
					mui.toast(res.msg);
					app.out();
					return false;
				}

				if(res.status == 0) {
					mui.alert(res.msg);
				} else {
					document.getElementById('do_add').disabled = "";
					mui.toast(res.msg);
					mui.fire(plus.webview.getWebviewById('shop-manage.html'), 'refresh_data');
					mui.back();
					//location.href=location;
				}

			},
			error: function(xhr, type, errorThrown) {
				//console.log(JSON.stringify(xhr));
				//console.log(JSON.stringify(type));
				//console.log(JSON.stringify(errorThrown));
				mui.toast('操作失败！');
			}
		});
	}, false);

	mui('body').on('tap', '.mui-popover-action.original_img li>a', function() {
		var a = this,
			parent;
		//根据点击按钮，反推当前是哪个actionsheet
		for(parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
			if(parent.classList.contains('mui-popover-action')) {
				break;
			}
		}
		//关闭actionsheet
		mui('#' + parent.id).popover('toggle');
		if(a.getAttribute('data-id') == 'xiangce') {
			//从相册选择
			galleryImg('original_img');
			return false;
		}
		if(a.getAttribute('data-id') == 'paizao') {
			//拍照
			getImage('original_img');
			return false;
		}
	})

	mui('body').on('tap', '.mui-popover-action.goods_images li>a', function() {
		var a = this,
			parent;
		//根据点击按钮，反推当前是哪个actionsheet
		for(parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
			if(parent.classList.contains('mui-popover-action')) {
				break;
			}
		}
		//关闭actionsheet
		mui('#' + parent.id).popover('toggle');
		if(a.getAttribute('data-id') == 'xiangce') {
			//从相册选择
			galleryImg('goods_images');
			return false;
		}
		if(a.getAttribute('data-id') == 'paizao') {
			//拍照
			getImage('goods_images');
			return false;
		}
	})

	mui('body').on('tap', '.mui-popover-action.goods_detail li>a', function() {
		var a = this,
			parent;
		//根据点击按钮，反推当前是哪个actionsheet
		for(parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
			if(parent.classList.contains('mui-popover-action')) {
				break;
			}
		}
		//关闭actionsheet
		mui('#' + parent.id).popover('toggle');
		if(a.getAttribute('data-id') == 'xiangce') {
			//从相册选择
			galleryImg('goods_detail');
			return false;
		}
		if(a.getAttribute('data-id') == 'paizao') {
			//拍照
			getImage('goods_detail');
			return false;
		}
	})

	//拍照
	function getImage(type) {
		var c = plus.camera.getCamera();
		c.captureImage(function(e) {
			plus.io.resolveLocalFileSystemURL(e, function(entry) {
				var s = entry.toLocalURL() + "?version=" + new Date().getTime();
				console.log(s);
				uploadImg(s, type);
				/*
				if(type=='original_img'){
					document.getElementById('upload_original_img').innerHTML='已选择图片';
					document.getElementById('original_img').src=s;
				}
				else if(type=='goods_images'){					
					if($('.add-img .des-img #goods_images li').length==5){
					    mui.alert('最多可添加5张图片');
					    return false;
					}
					var htm='';
					htm+='<li>';
					htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
					htm+='<img src="'+s+'" width="34px" height="34px" />';
					htm+='</li>';
					$('.add-img .des-img #goods_images').append(htm);
				}
				else if(type=='goods_detail'){
					if($('.goods-des .des-img #goods_detail_img li').length==3){
					    mui.alert('最多可添加3张图片');
					    return false;
					}
					var htm='';
					htm+='<li>';
					htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
					htm+='<img src="'+s+'" width="40px" height="40px" />';
					htm+='</li>';
					$('.goods-des .des-img #goods_detail_img').append(htm);
				}*/
				//变更大图预览的src
				//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
				document.querySelector("#__mui-imageview__group .mui-slider-item img").src = s + "?version=" + new Date().getTime();
			}, function(e) {
				console.log("读取拍照文件错误：" + e.message);
			});
		}, function(s) {
			console.log("error" + s);
		}, {
			filename: "_doc/head.jpg"
		})
	}

	//相册
	function galleryImg(type) {
		plus.gallery.pick(function(a) {
			plus.io.resolveLocalFileSystemURL(a, function(entry) {
				plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
					root.getFile("head.jpg", {}, function(file) {
						//文件已存在
						file.remove(function() {
							console.log("file remove success");
							entry.copyTo(root, 'head.jpg', function(e) {
									var e = e.fullPath + "?version=" + new Date().getTime();
									uploadImg(e, type);
									/*
									if(type=='original_img'){
										document.getElementById('upload_original_img').innerHTML='已选择图片';
									    document.getElementById('original_img').src=e;
									}
									else if(type=='goods_images'){
										//document.getElementById("headimg").src = s;
										//uploadImg(s);
										if($('.add-img .des-img #goods_images li').length==5){
										    mui.alert('最多可添加5张图片');
										    return false;
										}
										var htm='';
										htm+='<li>';
										htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
										htm+='<img src="'+e+'" width="34px" height="34px" />';
										htm+='</li>';
										$('.add-img .des-img #goods_images').append(htm);
										
									}
									else if(type=='goods_detail'){
										if($('.goods-des .des-img #goods_detail_img li').length==3){
										    mui.alert('最多可添加3张图片');
										    return false;
										}
										var htm='';
										htm+='<li>';
										htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
										htm+='<img src="'+e+'" width="40px" height="40px" />';
										htm+='</li>';
										$('.goods-des .des-img #goods_detail_img').append(htm);
									}
									*/
									//变更大图预览的src
									//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
									document.querySelector("#__mui-imageview__group .mui-slider-item img").src = e + "?version=" + new Date().getTime();;
								},
								function(e) {
									console.log('copy image fail:' + e.message);
								});
						}, function() {
							console.log("delete image fail:" + e.message);
						});
					}, function() {
						//文件不存在
						entry.copyTo(root, 'head.jpg', function(e) {
								var path = e.fullPath + "?version=" + new Date().getTime();
								document.getElementById("headimg").src = path;
								//document.getElementById("head-img1").src = path;
								//变更大图预览的src
								//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
								document.querySelector("#__mui-imageview__group .mui-slider-item img").src = path;
							},
							function(e) {
								console.log('copy image fail:' + e.message);
							});
					});
				}, function(e) {
					console.log("get _www folder fail");
				})
			}, function(e) {
				console.log("读取拍照文件错误：" + e.message);
			});
		}, function(a) {}, {
			filter: "image"
		})
	}

	//压缩图片   成64位编码
	function uploadImg11(path) {
		var img = new Image();
		img.src = path;
		//生成比例 
		var w = img.width,
			h = img.height,
			scale = w / h;

		//console.log(img.width);
		//console.log(img.height);
		w = 480 || w; //480  你想压缩到多大
		h = w / scale;
		//生成canvas
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		canvas.setAttribute('width', w);
		canvas.setAttribute('height', h);
		ctx.drawImage(img, 0, 0, w, h);
		var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1z 表示图片质量，越低越模糊。	 
		//console.log(base64);
		base64 = base64.replace('data:image/jpeg;base64,', '');
		return base64;
	}

	function uploadImg(path, type) {
		var direct = 'goods/' + type;
		if(type == 'goods_detail') {
			direct = 'goods/goods_detail_images';
		}
		var img = new Image();
		img.src = path;
		img.onload = function() {
			var that = this;
			//生成比例 
			var w = that.width,
				h = that.height,
				scale = w / h;
			w = 480 || w; //480  你想压缩到多大
			h = w / scale;

			//生成canvas
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			canvas.setAttribute('width', w);
			canvas.setAttribute('height', h);
			ctx.drawImage(that, 0, 0, w, h);
			var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1z 表示图片质量，越低越模糊。	 
			console.log(base64);
			console.log(uploadurl);
			//base64 = base64.replace('data:image/jpeg;base64,', '');
			mui.post(uploadurl, {
				file: base64,
				uid: uid,
				path: path,
				name: direct
			}, function(res) {
				console.log(JSON.stringify(res));
				if(res.status > 0) {
					//var img_path=serverurl + 'Uploads/trade/' + trade_id + '.jpg';
					var img_path = res.url;
					mui.toast('上传成功！');
					if(type == 'original_img') {
						document.getElementById('upload_original_img').innerHTML = '已选择图片';
						document.getElementById('original_img').src = img_path;
						document.getElementById('original_img').style.display = "block";
					} else if(type == 'goods_images') {
						if($('.add-img .des-img #goods_images li').length == 5) {
							mui.alert('最多可添加5张图片');
							return false;
						}
						var htm = '';
						htm += '<li>';
						htm += '<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
						htm += '<img src="' + img_path + '" width="34px" height="34px" />';
						htm += '</li>';
						$('.add-img .des-img #goods_images').append(htm);
					} else if(type == 'goods_detail') {
						if($('.goods-des .des-img #goods_detail_img li').length == 3) {
							mui.alert('最多可添加3张图片');
							return false;
						}
						var htm = '';
						htm += '<li>';
						htm += '<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
						htm += '<img src="' + img_path + '" width="40px" height="40px" />';
						htm += '</li>';
						$('.goods-des .des-img #goods_detail_img').append(htm);
					}

				}
			}, 'json');

		}
	}

});

//删除图片
function del_img(obj) {
	var liob = $(obj).parent('li');
	liob.remove();
}